#!/bin/sh

source ./projects-list.sh

function getmd5() {
	local atmp=$(echo $1 | md5sum | tr '[a-z]' '[A-Z]')
	echo $(echo "${atmp:0:8}-${atmp:8:4}-${atmp:12:4}-${atmp:16:4}-${atmp:20:12}")
}

depend_projects=
sln_projects=
sln_sections=

function build_lib() {
	local name=$1
	local finger=$(getmd5 $name)
	echo "build project: $name, finger: $finger"
	sln_projects=$sln_projects"Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"$name\", \"projects\\$name.vcxproj\", \"{$finger}\"
EndProject
"
	depend_projects=$depend_projects"\t\t{$finger} = {$finger}\n"
	sln_sections=$sln_sections"{$finger}.Debug|x64.ActiveCfg = Debug|x64
		{$finger}.Debug|x64.Build.0 = Debug|x64
		{$finger}.Release|x64.ActiveCfg = Release|x64
		{$finger}.Release|x64.Build.0 = Release|x64
		"
	cat projects/_template.vcxproj | sed 's/template_finger/'$finger'/g' > projects/$name.vcxproj
	cp -f projects/_template.vcxproj.filters projects/$name.vcxproj.filters
}

function build_sln() {
	echo "
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.40629.0
MinimumVisualStudioVersion = 10.0.40219.1
Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"nginx\", \"projects\nginx.vcxproj\", \"{580EBB9E-5C20-43E5-9B6D-3AE238771A88}\"
	ProjectSection(ProjectDependencies) = postProject
$depend_projects
	EndProjectSection
EndProject
${sln_projects}Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|x64 = Debug|x64
		Release|x64 = Release|x64
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{580EBB9E-5C20-43E5-9B6D-3AE238771A88}.Debug|x64.ActiveCfg = Debug|x64
		{580EBB9E-5C20-43E5-9B6D-3AE238771A88}.Debug|x64.Build.0 = Debug|x64
		{580EBB9E-5C20-43E5-9B6D-3AE238771A88}.Release|x64.ActiveCfg = Release|x64
		{580EBB9E-5C20-43E5-9B6D-3AE238771A88}.Release|x64.Build.0 = Release|x64
		${sln_sections}
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal" > openresty.sln
}

if [ $# -gt 0 ]; then
	for arg in $@; do
		build_lib $arg
	done
	exit 0
fi

for index in ${!projects[@]}; do
	build_lib ${projects[$index]}
done

build_sln